package org.wmq.travelagency02.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wmq.travelagency02.mapper.ChatGroupMapper;
import org.wmq.travelagency02.model.Entity.ChatGroup;
import org.wmq.travelagency02.model.Entity.ChatGroupMember;
import org.wmq.travelagency02.model.Entity.ChatUser;
import org.wmq.travelagency02.model.Entity.ContactGroup;
import org.wmq.travelagency02.model.VO.ChatGroupQueryVO;
import org.wmq.travelagency02.service.ChatGroupMemberService;
import org.wmq.travelagency02.service.ChatGroupService;
import org.wmq.travelagency02.service.ContactGroupService;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatGroupServiceImpl extends ServiceImpl<ChatGroupMapper, ChatGroup> implements ChatGroupService {
    private final ChatGroupMapper chatGroupMapper;
    private final ContactGroupService contactGroupService;
    @Autowired
    private ChatGroupMemberService chatGroupMemberService;

    @Override
    public ChatGroupQueryVO getChatGroupQueryVOById(String id) {
        ChatGroup chatGroup = this.lambdaQuery().eq(ChatGroup::getId, id)
                .select(ChatGroup::getName, ChatGroup::getOwnerId, ChatGroup::getMaxSize)
                .one();
        if (chatGroup == null){
            return null;
        }
        ChatGroupQueryVO result = new ChatGroupQueryVO();
        BeanUtils.copyProperties(chatGroup, result);
        result.setId(id);
        List<ChatUser> chatUserList = this.chatGroupMemberService.getChatUserListByChatGroupId(id);
        result.setChatUserList(chatUserList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeChatGroupById(String id) {
        boolean success = this.removeById(id);
        if (!success){
            return false;
        }
        try {
            this.chatGroupMemberService.lambdaUpdate().eq(ChatGroupMember::getChatGroupId, id)
                    .remove();
        } catch (Exception e) {
            throw new RuntimeException("删除ChatGroupMember时发生异常", e);
        }
        return true;
    }

}
